<template>
  <div>
    <myDivider name="用户管理"></myDivider>
    <el-page-header @back="goBack" :content="'账号与人口信息绑定'">
    </el-page-header>
    <div class="bindingInfo">


      <el-form ref="insertForm" :model="insertForm" label-width="80px" :inline="true" :rules="insertRules">

        <el-form-item label="账号:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
          <el-input v-model="insertForm.account" autocomplete="off" style="width: 262px" disabled="disabled"></el-input>
        </el-form-item>

        <el-form-item label="用户名:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
          <el-input v-model="insertForm.userName" autocomplete="off" style="width: 262px"
            disabled="disabled"></el-input>
        </el-form-item>

        <el-form-item label="角色:" :label-width="formLabelWidth" class="formItemStyle">
          <div class="block">
            <el-input v-model="insertForm.roleNames" autocomplete="off" style="width: 262px"
              disabled="disabled"></el-input>
            <!-- <el-select placeholder="" v-model="insertForm.roleIds" multiple clearable filterable disabled="disabled"
              style="width: 262px">
              <el-option v-for="item in allRoleListData" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select> -->
          </div>
        </el-form-item>

        <el-form-item label="绑定部门:" :label-width="formLabelWidth" class="formItemStyle">
          <div class="block">
            <el-input v-model="insertForm.departmentName" style="width: 262px" disabled></el-input>
            <!-- <el-cascader v-model="insertForm.depId" placeholder="" :options="depmentManageData" filterable
              disabled="disabled" :props="{ checkStrictly: true }" clearable style="width: 262px"></el-cascader> -->
          </div>
        </el-form-item>

        <el-form-item label="当前绑定手机号:" :label-width="formLabelWidth" class="formItemStyle"
          prop="bindingPopulationPhoneNum">
          <el-input v-model="insertForm.bindingPopulationPhoneNum" autocomplete="off" style="width: 262px"
            disabled="disabled"></el-input>
        </el-form-item>

        <el-form-item label="用户状态:" :label-width="formLabelWidth" class="formItemStyle">
          <el-radio-group v-model="insertForm.status" disabled="disabled">
            <el-radio label='1'>正常</el-radio>
            <el-radio label='0'>禁用</el-radio>
          </el-radio-group>
        </el-form-item>



      </el-form>




    </div>
    <div style="padding-left:20px;box-sizing: border-box;">
      <el-divider></el-divider>
      <div>
        <!-- <span style="margin-left: 50px;">个人信息搜索</span> -->
        <div>
          <el-input class="findValue" v-model="query.name" placeholder="姓名" clearable
            @keyup.enter.native="SouSuo"></el-input>
          <el-input class="findValue" v-model="query.phoneNumber" placeholder="手机号" clearable
            @keyup.enter.native="SouSuo"></el-input>
          <el-select class="findValue" v-model="query.residentialId" clearable @change="SouSuo" placeholder="小区筛选">
            <el-option v-for="item, i in residentialData" :key="i" :label="item.name" :value="item.residentialId">
            </el-option>
          </el-select>
          <el-select class="findValue" v-model="query.specialCode" clearable @change="SouSuo" placeholder="身份标识筛选">
            <el-option v-for="item, i in specialCodeData" :key="i" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
          <el-button type="primary" style="margin-top: 20px; margin-left: 15px" icon="el-icon-search"
            @click="SouSuo">搜索</el-button>
        </div>

        <div>
          <el-table :data="userData" style="width: 100%" class="menuTable" row-key="uid"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">


            <el-table-column prop="name" label="姓名" align="center">
            </el-table-column>
            <el-table-column prop="phoneNumber" label="手机号" width="120" align="center">
            </el-table-column>
            <el-table-column prop="bindingUserAccount" label="已绑定账号" width="150" align="center">
            </el-table-column>


            <el-table-column prop="gender" label="性别" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.gender == '0' ? '女' : "男" }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="birthday" label="出生日期" align="center">

              <template slot-scope="scope">
                {{ timeFormat(scope.row.birthday) }}
              </template>
            </el-table-column>

            <el-table-column prop="maritalStatusValue" label="婚否" align="center">
            </el-table-column>


            <el-table-column align="center" prop="specialNames" label="身份标识" width="150">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.specialNames" placement="top-start">
                  <span>{{ scope.row.specialNames == null ? '—' : scope.row.specialNames.length > 8 ?
                    "..." + scope.row.specialNames.substring(scope.row.specialNames.length - 8,
                      scope.row.specialNames.length) : scope.row.specialNames }}</span>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="residentialNames" label="所属小区" width="150">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.residentialNames" placement="top-start">
                  <span>{{ scope.row.residentialNames == null ? '—' : scope.row.residentialNames.length > 8 ?
                    "..." + scope.row.residentialNames.substring(scope.row.residentialNames.length - 8,
                      scope.row.residentialNames.length) : scope.row.residentialNames }}</span>
                </el-tooltip>
              </template>
            </el-table-column>

            <el-table-column prop="homeAddress" label="家庭住址" align="center">

              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.homeAddress" placement="top-start">
                  <span>{{ scope.row.homeAddress == null ? '—' : scope.row.homeAddress.length > 8 ?
                    "..." + scope.row.homeAddress.substring(scope.row.homeAddress.length - 8,
                      scope.row.homeAddress.length) : scope.row.homeAddress }}</span>
                </el-tooltip>
              </template>
            </el-table-column>

            <!-- <el-table-column prop="educationLevelValue" label="文化程度">
          </el-table-column> -->


            <el-table-column prop="occupation" label="职业" align="center">
            </el-table-column>

            <el-table-column prop="company" label="工作单位" align="center">
            </el-table-column>

            <el-table-column prop="notes" label="备注" align="center">
            </el-table-column>



            <el-table-column label="操作" width="150px" align="center">

              <template slot-scope="scope">
                <el-button type="success" round size="mini" @click="bindingPopulationInfo(scope.row)">绑定</el-button>
                <el-button type="danger" round size="mini" @click="unbindingPopulationInfo(scope.row)">解绑</el-button>
              </template>
            </el-table-column>
          </el-table>



        </div>

        <div class="pageFooterFather">
          <myPagination :total="totalSize" :pageNum="pageNum" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
          </myPagination>
        </div>



      </div>
    </div>

  </div>
</template>

<style scoped>
.bindingInfo {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 10px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 200px;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  /* margin-left: 22px; */
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}


.birthdayDateItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}
</style>



<script>
import {
  getPopulationList,
  updatePopulationInfo,

} from "../population/population";
import {
  binding,
  unbinding,

} from "./user";

import {
  getFatherDepList,
} from "../department/department";
import { timeYMD } from "@/utils/utils.js";
export default {
  data() {
    return {
      userData: [], //用户数据
      formLabelWidth: "120px", //控制前面label的宽度
      insertForm: {
        // 新增弹框参数
        userName: "",
        account: "",
        roleIds: "",
        depId: "",
        status: "",
        bindingPopulationPhoneNum: "",
      },
      insertRules: {
        phoneNumber: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "设备名称不能为空",
            trigger: "blur",
          },
        ],
      },
      genderListData: [
        { id: '0', name: "女" }, { id: '1', name: "男" }
      ],
      residentialStatusOpion: [
        { id: '0', name: "空置" }, { id: '1', name: "在住" }
      ],
      maritalStatusOptionData: [
        { id: 0, name: "单身" }, { id: 1, name: "未婚" }, { id: 2, name: "已婚" }
      ],
      isPartyMemberOptionData: [
        { id: 0, name: "否" }, { id: 1, name: "是" }
      ],
      depmentManageData: [],
      allRoleListData: [],
      query: {
        name: "",
        account: ""
      },
      userAccountId: "",
      populationInformationId: "",
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      residentialData: [],
      specialCodeData: [],
    }
  },

  async activated() {
    this.getSpecialCodeArray()
    this.getResidentialData()
    let userData = JSON.parse(sessionStorage.getItem('logOnUser'))
    let unitType = userData.unitType;
    let unitId = userData.unitId;
    let unitName = userData.unitName;
    let res = await this.$api.system.myGetUserInfoById({
      "userId": this.$route.query.id, //用户id  必填
      "unitType": unitType, //必填 和登录账号一致 机关：agency  机构：company  系统：system 
      "unitId": unitId, //系统传0 单位的必传
      "unitName": unitName //系统"",单位的必传
    })
    if (res.code == 200) {
      var user = res.data;
      var depId = eval('([' + user.depIds + '])');
      this.insertForm.id = user.id,
        this.userAccountId = this.insertForm.id;
      this.insertForm.account = user.account;
      this.insertForm.userName = user.name;
      this.insertForm.roleNames = user.roleNames;
      this.insertForm.roleIds = user.roleIds
      this.insertForm.depId = depId;

      this.insertForm.departmentName = user.departmentName

      this.insertForm.status = user.status + '';
      this.insertForm.bindingPopulationPhoneNum = user.bindingPopulationPhoneNum;
      console.info(this.insertForm.bindingPopulationPhoneNum);
    } else {
      this.$message.error(res.message)
    }


    // getFatherDepList().then((res) => {
    //   this.depmentManageData = res;
    // });


    //刚进入页面加载
    this.getPopulationList();

  },
  mounted: function () {
    //初始化选项数据

  },
  methods: {
    async getSpecialCodeArray() {
      let res = await this.$api.customer.myDictionaryQueryList('special_code')
      if (res.code == 200) {
        this.specialCodeData = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    async getResidentialData() {
      let res = await this.$api.patrol.myPatrolGetCommunityList('')
      if (res.code == 200) {
        this.residentialData = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    PageChange(e) {//分页器——页数变化
      this.pageNum = e
      this.getPopulationList()
    },
    pageSizeChange(e) { //分页器——每页数量变化
      this.pageNum = 1
      this.pageSize = e
      this.getPopulationList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getPopulationList()
    },




    /**
     *  修改
     */
    onSubmitUpdate() {
      this.insertForm.id = this.$route.query.id;
      updatePopulationInfo(this.insertForm).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '个人信息修改成功',
            type: 'success'
          });
          this.goBack();
        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }

      })
    },

    /**
     *  上一页
     */
    goBack() {
      // this.$router.go(-1)
      this.$router.push({ path: '/user/userManage' });
    },

    //按条件查询菜单列表
    getPopulationList() {

      getPopulationList({
        name: this.query.name,
        phoneNumber: this.query.phoneNumber,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        specialCode: this.query.specialCode ? this.query.specialCode : '',
        "residentialId": this.query.residentialId ? this.query.residentialId : 0, //小区id
      }).then((res) => {
        if (res.code == 200) {
          if (res.data.list.length < 1 && this.pageNum != 1) { //判断，当搜索关键字有内容时，我直接点击分页，会造成关键词列表中没有某某页的数据，那么我就用第一页重新请求一次
            this.pageNum = 1
            this.getPopulationList()
            return
          }
          this.userData = res.data.list;
          this.totalSize = res.data.total;
        } else {
          this.$message.error(res.message)
        }

      });
    },

    timeFormat(time) {
      return timeYMD(time);
    },
    bindingPopulationInfo(row) {
      this.populationInformationId = row.id;

      if (this.insertForm.account != row.phoneNumber) {
        this.$confirm("检测到绑定手机号与账号不一致，是否确认该操作", "提示", {
          iconClass: "el-icon-question",//自定义图标样式
          confirmButtonText: "确认",//确认按钮文字更换
          cancelButtonText: "取消",//取消按钮文字更换
          showClose: true,//是否显示右上角关闭按钮
          type: "warning",//提示类型  success/info/warning/error
        }).then(() => {
          //确认操作
          this.doBinding(row.phoneNumber);

        }).then((data) => {
          //取消操作
        }).catch((err) => {
          //捕获异常
          console.log(err);
        });

      } else {
        this.doBinding(row.phoneNumber);
      }

    },

    doBinding(phoneNumber) {
      binding(this.userAccountId, this.populationInformationId, 'user_account').then((res) => {
        if (res.code == 200) {
          this.$message({
            message: '绑定成功',
            type: 'success'
          })
          this.$nextTick(() => {
            this.insertForm.bindingPopulationPhoneNum = phoneNumber;
            this.getPopulationList();
          })

        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }

      });
    },

    unbindingPopulationInfo(row) {
      this.$confirm('此操作将会解绑, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.populationInformationId = row.id;
        unbinding(this.userAccountId, this.populationInformationId).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '解绑成功',
              type: 'success'
            })
            this.$nextTick(() => {
              this.insertForm.bindingPopulationPhoneNum = "未绑定";
              this.userData = [];
              this.getPopulationList();
            })

          } else {
            this.$message({
              message: res.message,
              type: "warning",
            });
          }

        });
      }).catch(() => {

      });

    }


  }
};
</script>